package org.java.web;

import com.alibaba.fastjson.JSON;
import org.java.dao.ArtGoodsDao;
import org.java.dao.DaoImpl.GoodsDaoImpl;
import org.java.entity.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/goods")
public class GoodsServlet extends BaseServlet{
    private ArtGoodsDao dao=new GoodsDaoImpl();
    //商场页面的数据初始化
    protected void mallInit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取新的page页
        String newpage = request.getParameter("page");
        //实现type分类查询
        String type = request.getParameter("type");
        String size = request.getParameter("size");
        String price = request.getParameter("price");
//        //判断用户是否选择条件查询
//        if(type!=null&&!type.equals("")){
//            request.getSession().setAttribute("type",type);
//        }
//        if(size!=null&&!size.equals("")){
//            request.getSession().setAttribute("size",size);
//        }
//        if(price!=null&&!price.equals("")){
//            request.getSession().setAttribute("price",price);
//        }
//        //将选择的type存入session中 让用户分页跳转后任然是该类型的商品
//        String typeyse =(String) request.getSession().getAttribute("type");
//        String newsize=(String) request.getSession().getAttribute("size");
//        String newprice=(String) request.getSession().getAttribute("price");

//        System.out.println(size);


        /**分页效果实现***/
        int page=1;  //初始第一页
        int rows=9;
        int count=dao.goodCount(type,size,price);
        int MaxPage=count%rows==0?count/rows:(count/rows)+1;

        //实时分页效果代码
        if(newpage!=null&&!newpage.equals("")){
            page=Integer.parseInt(newpage);
        }

        //创建好新集合用于存放不同数据
        Map allInfo=new HashMap();


        /**queryForList的方式取出数据，没有用实体类***/
        List<Map<String, Object>> list = dao.mailInit(page,rows,type,size,price);

        //往map集合里放入不同的数据
        allInfo.put("list",list);
        allInfo.put("maxpage",MaxPage);
        //设置输出流
        String json = JSON.toJSONString(allInfo);
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(json);

        //关闭流
        out.flush();
        out.close();
    }
    //分页
    protected void goods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得分页的参数page，rows
        //获得当前页
        Integer page=Integer.parseInt(request.getParameter("page"));
        //获得每一页显示的条数
        Integer rows=Integer.parseInt(request.getParameter("rows"));
        //计算总条数
        Integer count = dao.goodCount();
        //计算总页数
        Integer maxPage=count % rows ==0 ? count / rows : count / rows + 1;
        //得到集合----分页查询
        List<Goods> list = dao.getGoodsList(page,rows);
        //封装到map中
         Map map=new HashMap();
         map.put("pageNum",page);//当前页
         map.put("rows",rows);//每页显示条数
         map.put("count",count);//总记录数
         map.put("maxPage",maxPage);//总页数1
         map.put("list",list);//集合
        //创建流，用于返回json数据
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //将对象转换成json
        String json = JSON.toJSONString(map);
        //输出json
        out.write(json);
        out.flush();
        out.close();
    }

    //点击购买按钮  mall.jsp ----> pro_detail.jsp
    protected void buyGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String goodsId = request.getParameter("goodsId");

        //通过GoodsId获取商品对象
        Goods goods=dao.getOneGoods(goodsId);
        //取到对象，存入，跳转至下个页面
        request.setAttribute("goods",goods);
        request.getRequestDispatcher("pro_detail.jsp").forward(request,response);
    }

    /**
     * 从pro 购买 到 jisuan.jsp页面 购买单个商品
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void buyOneGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String goodsId = request.getParameter("goodsId");
        String buyCount = request.getParameter("count");
        String userId =(String) request.getSession().getAttribute("userId");

        //获取已需要的参数  开始showtime


    }

    //查询单个商品的库存量
    protected void queryCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String gid = request.getParameter("gid");
        Integer count=dao.queryCount(gid);
        String json = count.toString();

        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }

    /**
     * pro_detail界面加入购物车方法
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void collect(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String goodsId = request.getParameter("goodsId");
        String count = request.getParameter("count");
        String userId = (String) request.getSession().getAttribute("userId");

        //根据userid和goodsid查看之前是否已加入购物车
        //有的话加则提醒用户已在购物车，没有就加入
        boolean falg=dao.addCart(userId,goodsId);
//        System.out.println(falg);
        String rollback="";
        if(falg){
            //已有改商品
            rollback="no";
        }else {
            //可以添加到购物车
            int i = Integer.parseInt(count);
            dao.addGoodsInCart(userId,goodsId,i);
            rollback="yes";
        }
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(rollback);
        out.flush();
        out.close();
    }

    /**
     * mall界面点击加入购物车
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void mallAddCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String goodsId = request.getParameter("goodsId");
        //获取session中的用户id
        String userId =(String)request.getSession().getAttribute("userId");
        boolean flag = dao.addCart(userId, goodsId);
        System.out.println(flag);
        String rollback;
        /**先判断用户是否登录 ， 没登陆跳转登录页面**/
        if(userId!=null&&!userId.equals("")){
            if(flag){
                //已有改商品
                rollback="no";
            }else {
                //可以添加到购物车
                dao.addGoodsInCart(userId,goodsId,1);
                rollback="yes";
            }
        }else {
            rollback="没登陆";
        }


        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(rollback);
        System.out.println(rollback);
        out.flush();
        out.close();
    }
}
